from django.core.management.base import BaseCommand
from django.utils import timezone
from activity.models import Activity

class Command(BaseCommand):
    help = '更新活动状态 - 根据时间自动将活动状态从一个转换到另一个'
    
    def handle(self, *args, **kwargs):
        now = timezone.now()
        updated_activities = 0
        
        # 1. 将已达到报名截止时间但尚未开始的活动从 'registration_open' 转换为 'not_started'
        # 注意：这里的逻辑需要根据实际业务需求调整
        # 实际上，'not_started' 通常是在活动创建时设置，表示还未开始报名
        # 以下是示例逻辑，实际应根据项目需求调整
        
        # 2. 将已开始但尚未结束的活动状态转换为 'ongoing'
        ongoing_activities = Activity.objects.filter(
            status__in=['not_started', 'registration_open'],
            start_time__lte=now,
            end_time__gt=now
        ).update(status='ongoing')
        updated_activities += ongoing_activities
        
        # 3. 将已结束的活动状态转换为 'completed'
        completed_activities = Activity.objects.filter(
            status='ongoing',
            end_time__lte=now
        ).update(status='completed')
        updated_activities += completed_activities
        
        self.stdout.write(self.style.SUCCESS(f'成功更新了 {updated_activities} 个活动的状态'))